﻿using UnityEngine;
using System.Collections;

public class TrainLinkerScript : MonoBehaviour {
	
	Transform pullingMe;
	public float distToPieces = 1.0f;
	float FollowSpead = 0.1f;
	public Transform imPulling;
	public int myIndex;

	public GameObject[] DestroyCarriageGibs;
	public LinkedCarriageCration myCreator;


	public void WasCreated(Transform connectTo, GameObject carriageToCreate,  int Index, LinkedCarriageCration creator, Transform voluntaryTrans = null)
	{
		AttachToObject (connectTo);
		CreateCariage (carriageToCreate, voluntaryTrans);
		myIndex = Index;
		myCreator = creator;
	}


	// Update is called once per frame
	void Update () 
	{
		//if this linker is attached to something, follow it
		if(pullingMe)
		{
			Vector3 moveToPos = pullingMe.transform.position - pullingMe.forward  * distToPieces;
			transform.LookAt (moveToPos);
			transform.position = Vector3.Lerp (transform.position, moveToPos, 0.1f);
		}
	}


	float explodepointRadius = 0.3f;
	float explodeRadius = 2.0f;
	float explodeForce = 100.0f;
	public void DestroyLinkAndCarriage()
	{
		foreach(GameObject gib in DestroyCarriageGibs)
		{
			GameObject instance = Instantiate(gib, transform.position + Random.insideUnitSphere * explodepointRadius, Quaternion.identity ) as GameObject;
			instance.rigidbody.AddExplosionForce(explodeForce, transform.position, explodeRadius);
		}

		if(myCreator != null)
			myCreator.RemoveThisLink(gameObject);

		Destroy (imPulling.gameObject);
		Destroy (gameObject);
	}


	public void CreateCariage(GameObject carriageToCreate, Transform startTran = null)
	{
		GameObject instance;
		if(startTran == null)
			instance = Instantiate (carriageToCreate, transform.position - transform.forward, Quaternion.identity) as GameObject;
		else
			instance = Instantiate (carriageToCreate, startTran.position, startTran.rotation) as GameObject;
	
		instance.GetComponent<CarriageScriptBase> ().SetUpCarriage (gameObject, distToPieces, FollowSpead);

		imPulling = instance.transform;
	}

	public void AttachToObject(Transform objectToFollow)
	{
		pullingMe = objectToFollow.transform;
	}
	
}